package api

import (
	"demo/enum"
	model "demo/models"
	"demo/models/response"
	"demo/service"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"strconv"
)

type UserController struct{}

var userService = service.UserService{}

// GetUserById GetById @Summary 获取用户id获取用户信息
func (u *UserController) GetUserById(c *gin.Context) {
	id := c.Query("id")
	userInfo := userService.GetUserById(id)
	response.Result(200, userInfo, "success", c)
}

// GetUserList 获取用户列表
func (u *UserController) GetUserList(c *gin.Context) {
	userList := userService.GetAllUsers()
	response.Result(200, userList, "success", c)
}

// GetUserListByPage 获取用户列表分页
func (u *UserController) GetUserListByPage(c *gin.Context) {
	currentPage := c.Query("currentPage")
	pageSize := c.Query("pageSize")
	currentPageInt, _ := strconv.Atoi(currentPage)
	pageSizeInt, _ := strconv.Atoi(pageSize)
	userList := userService.GetAllUsersByPage(currentPageInt, pageSizeInt)
	response.Result(200, userList, "success", c)
}

// CreateUser 创建用户
func (u *UserController) CreateUser(c *gin.Context) {
	var user model.User
	err := c.ShouldBind(&user)
	if err != nil {
		response.Result(401, nil, "参数错误", c)
	}
	validate := validator.New()
	err = validate.Struct(user)
	if err != nil {
		response.Result(401, nil, "参数校验失败", c)
		return
	}
	result := userService.CreateUser(user)
	response.Result(200, result, "success", c)
}

// DeleteUserById 更新用户信息
func (u *UserController) DeleteUserById(c *gin.Context) {
	id := c.Query("id")
	if id == "" {
		response.Result(401, nil, "id不能为空", c)
	}
	result := userService.DeleteUserById(id)
	response.Result(200, result, "success", c)
}

// UpdateUserById 更新用户信息
func (u *UserController) UpdateUserById(c *gin.Context) {
	var user model.User
	err := c.ShouldBind(&user)
	fmt.Println(user)
	fmt.Println(user.Sex == enum.MALE)
	if err != nil {
		response.Result(401, nil, "参数错误", c)
	} else {
		result := userService.UpdateUserById(user)

		response.Result(200, result, "success", c)
	}

}
